package base.thread_JUC2.chapter01.demo010;

import java.util.concurrent.TimeUnit;

/**
 * Result：模拟查询的结果
 *
 */
public class TestCase {

    public static void main(String[] args) {
        ThreadGroup threadGroup = new ThreadGroup("searcher");
        Result result = new Result();
        SearchTask searchTask = new SearchTask(result);


        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(threadGroup, searchTask);
            thread.start();

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.printf("存活线程数: %d\n", threadGroup.activeCount());
        System.out.printf("Information about the Thread Group\n");
        threadGroup.list();

        Thread[] threads = new Thread[threadGroup.activeCount()];
        // 线程组中线程拷贝到线程数组中
        threadGroup.enumerate(threads);
        for (int i = 0; i < threads.length; i++) {
            System.out.printf("%s -> %s\n", threads[i].getName(), threads[i].getState());
        }

        // main线程等待线程组中至少有一个线程结束，并开始打断线程组中所有线程
        waitFinish(threadGroup);
        threadGroup.interrupt();
    }

    public static void waitFinish(ThreadGroup group) {
        while (group.activeCount()==5) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
